package com.greenova.projector.dao;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.greenova.projector.entity.Person;
import com.greenova.projector.entity.Project;

@Repository
public class PersonDaoImpl implements PersonDao {

	@Autowired
	private HibernateTemplate hibernateTemplate;

	@Override
	public void addPerson(Person person) {
		hibernateTemplate.save(person);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Person> listAllPersons() {
		return hibernateTemplate.find("from Person");
	}

	@SuppressWarnings("unchecked")
	@Override
	public Set<Person> listAllPersonsNotAssignedInProject(long projectId) {
		// return
		// hibernateTemplate.find("from Person where id not in (select person_id from PROJECT_PERSON where project_id = "
		// + projectId + ")" );

		SessionFactory sessionFactory = hibernateTemplate.getSessionFactory();
		Session session = sessionFactory.openSession();

		Criteria a = session.createCriteria(Project.class).add(Restrictions.eq("id", projectId));
		 Project project = (Project) a.list().get(0);
		 Set<Person> assignedPersons = project.getPersons();
		//return assignedPersons;
		 
		 Criteria b = session.createCriteria(Person.class);
		 List<Person> persons = b.list();
		 persons.removeAll(assignedPersons);
		 
		 return new HashSet<Person>(persons);
//		Criteria c = session.createCriteria(Person.class)
//				//.add(Restrictions.sqlRestriction("id not in (select person_id from PROJECT_PERSON where project_id = 2"));
//		return c.list();

		 
	}

	@Override
	public Person getPersonById(long personId) {
		SessionFactory sessionFactory = hibernateTemplate.getSessionFactory();
		Session session = sessionFactory.openSession();
		
		Criteria crit = session.createCriteria(Person.class).add(Restrictions.eq("id", personId));
		Person person = (Person) crit.uniqueResult();
		session.close();
		return person;
		
	}

	@Override
	public Set<Person> listAllPersonsAssignedInProject(long projectId) {
		SessionFactory sessionFactory = hibernateTemplate.getSessionFactory();
		Session session = sessionFactory.openSession();

		Criteria a = session.createCriteria(Project.class).add(Restrictions.eq("id", projectId));
		 Project project = (Project) a.list().get(0);
		 Set<Person> assignedPersons = project.getPersons();
		 session.close();
		 return assignedPersons;
	}

	@Override
	public void updatePerson(Person person) {
		hibernateTemplate.update(person);
		
	}

	
	
}
